package net.awpspace.mp3player.screen;

import java.io.IOException;
import java.util.Random;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;

import com.nokia.mid.ui.CategoryBar;
import com.nokia.mid.ui.ElementListener;
import com.nokia.mid.ui.IconCommand;

import net.awpspace.mp3player.Application;
import net.awpspace.mp3player.entity.FavoriteList;
import net.awpspace.mp3player.entity.Mp3File;
import net.awpspace.mp3player.utils.AudioManager;
import net.awpspace.mp3player.utils.DAO;

public class PlayScreen extends GameCanvas implements CommandListener,
		ElementListener {

	static PlayScreen self;

	// Flag
	public static boolean isPlaying;
	static boolean isRepeat;
	static boolean isShuffle;
	boolean isChanging;

	static Mp3File currentFile;
	static int currentFileIndex;

	int volume;
	int startY = 130;
	int endY;

	// Command
	Command cmd_viewList;

	// Image & sprite
	Image img_bg;
	Image img_play;
	static Sprite sp_play;
	Image img_next;
	Image img_pre;
	Sprite sp_next;
	Sprite sp_pre;
	Image img_repeat;
	Sprite sp_repeat;
	Image img_shuffle;
	Sprite sp_shuffle;

	Image img_volume_up;
	Sprite sp_volume_up;
	Image img_volume_down;
	Sprite sp_volume_down;

	Image img_favorite;
	Sprite sp_favorite;
	
	Image img_bg_control;
	Image img_visual;
	
	Image img_bg_volume;

	// Vector list file
	static Vector list;

	public static PlayScreen getInstance(){
		if(self==null)
			self = new PlayScreen(null);
		return self;
	}
	
	public void setCurrentFile(Mp3File file){
		currentFile = file;
	}
	
	public PlayScreen(Mp3File file) {
		super(false);
		setTitle("Music Player");
		init();
		init_graphics();
		init_command();
		init_list_file();

		if (file != null) {
			currentFile = file;
			playFile(file);
			sp_play.nextFrame();
			repaint();
		}
		createCategoryBar();
	}

	/*
	 * Init method
	 */
	private void init() {
		isPlaying = false;
		isRepeat = false;
		isShuffle = false;

		volume = 100;
	}

	private void init_graphics() {
		try {
			img_bg = Image.createImage("/bg.jpg");
			img_play = Image.createImage("/play.png");
			sp_play = new Sprite(img_play, 48, 48);
			img_next = Image.createImage("/next.png");
			sp_next = new Sprite(img_next, 48, 48);
			img_pre = Image.createImage("/pre.png");
			sp_pre = new Sprite(img_pre, 48, 48);
			img_repeat = Image.createImage("/repeat.png");
			sp_repeat = new Sprite(img_repeat, 30, 30);
			img_shuffle = Image.createImage("/shuffle.png");
			sp_shuffle = new Sprite(img_shuffle, 30, 30);
			img_volume_down = Image.createImage("/volume_down.png");
			sp_volume_down = new Sprite(img_volume_down, 30, 30);
			img_volume_up = Image.createImage("/volume_up.png");
			sp_volume_up = new Sprite(img_volume_up, 30, 30);
			img_favorite = Image.createImage("/favorites.png");
			sp_favorite = new Sprite(img_favorite, 22, 22);
			
			img_bg_control = Image.createImage("/bg_control.png");
			img_visual = Image.createImage("/visual.png");
			
			img_bg_volume = Image.createImage("/bg_volume.png");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void init_command() {
		cmd_viewList = new Command("Playlists", Command.SCREEN, 1);
		addCommand(cmd_viewList);
		this.setCommandListener(this);
	}

	private void init_list_file() {
		list = new Vector();
		list = DAO.getInstance().getListFile();
		currentFileIndex = 0;
		currentFile = (Mp3File) list.elementAt(currentFileIndex);
	}

	/*
	 * Paint methods
	 */
	public void paint(Graphics g) {
		drawImage(g, img_bg, 0, 0);
		drawImage(g, img_visual, 0, 0);
		drawImage(g, img_bg_volume, 210, 0);
		paint_button(g);
		draw_infomation(g);
	}

	private void drawImage(Graphics g, Image img, int x, int y) {
		g.drawImage(img, x, y, Graphics.TOP | Graphics.LEFT);
	}

	private void paint_button(Graphics g) {
		// TODO Auto-generated method stub
		drawImage(g, img_bg_control, 0, 210);
		
		sp_play.setPosition(100, 210);
		sp_play.paint(g);

		sp_pre.setPosition(40, 210);
		sp_pre.paint(g);

		sp_next.setPosition(160, 210);
		sp_next.paint(g);
		

		sp_repeat.setPosition(20, 260);
		sp_repeat.paint(g);

		sp_shuffle.setPosition(190, 260);
		sp_shuffle.paint(g);

		sp_volume_up.setPosition(210, 0);
		sp_volume_up.paint(g);

		sp_volume_down.setPosition(210, 130);
		sp_volume_down.paint(g);

		if (FavoriteList.getInstance().checkExis(currentFile))
			sp_favorite.setFrame(1);
		else
			sp_favorite.setFrame(0);
		sp_favorite.setPosition(110, 260);
		sp_favorite.paint(g);
	}

	private void draw_infomation(Graphics g) {
		g.setColor(255, 255, 250);
		g.drawString("" + volume, 212, 60, Graphics.TOP | Graphics.LEFT);
		g.drawString(currentFile.getFile_name(), 120, 185, Graphics.TOP
				| Graphics.HCENTER);
	}
	public static void setStateButtonPlay(int index){
		if(index <=1){
			sp_play.setFrame(index);
		}
	}

	// End paint methods

	/*
	 * Event Touch & Command
	 */
	protected void pointerPressed(int x, int y) {
		if (checkTouched(sp_play, x, y)) {
			System.out.println("touch play");
			sp_play.nextFrame();
			repaint();
			if (isPlaying == false) {
				playFile(currentFile);
				isPlaying = true;
			} else {
				isPlaying = false;
				AudioManager.getInstance().stopAll();
			}
		}
		if (checkTouched(sp_pre, x, y)) {
			System.out.println("touch pre");
			if (currentFileIndex > 0) {
				currentFileIndex--;
				currentFile = (Mp3File) list.elementAt(currentFileIndex);
			}else if(currentFileIndex==0){
				currentFileIndex=list.size()-1;
				currentFile=(Mp3File) list.elementAt(currentFileIndex);
			}
			AudioManager.getInstance().stopAll();
			repaint();
			if (isPlaying)
				playFile(currentFile);
		}
		if (checkTouched(sp_next, x, y)) {
			System.out.println("touch next");
			if (isShuffle) {
				Random rd = new Random();
				int size = list.size();
				currentFileIndex = rd.nextInt(size);
				currentFile = (Mp3File) list.elementAt(currentFileIndex);
			} else if (currentFileIndex < list.size() - 1) {
				currentFileIndex++;
				currentFile = (Mp3File) list.elementAt(currentFileIndex);
			}else if(currentFileIndex == list.size() - 1){
				currentFileIndex=0;
				currentFile=(Mp3File) list.elementAt(currentFileIndex);
			}
			AudioManager.getInstance().stopAll();
			repaint();
			if (isPlaying)
				playFile(currentFile);
		}
		if (checkTouched(sp_repeat, x, y)) {
			// sp_repeat.nextFrame();
			sp_repeat.nextFrame();
			repaint();
			isRepeat = !isRepeat;
			System.out.println("repeat: " + isRepeat);
		}
		if (checkTouched(sp_shuffle, x, y)) {
			// sp_repeat.nextFrame();
			sp_shuffle.nextFrame();
			repaint();
			isShuffle = !isShuffle;
			System.out.println("shuffle: " + isShuffle);
		}
		if (checkTouched(sp_volume_up, x, y)) {
			int i = volume / 10;
			if (i < 10)
				volume = (i + 1) * 10;
			else
				volume = 100;
			AudioManager.getInstance().setVolume(volume);
			repaint();
		}
		if (checkTouched(sp_volume_down, x, y)) {
			int i = volume / 10;
			if (i == 0)
				volume = 0;
			else
				volume = (i - 1) * 10;
			AudioManager.getInstance().setVolume(volume);
			repaint();
		}
		if (checkTouched(sp_favorite, x, y)) {
			sp_favorite.nextFrame();
			if (sp_favorite.getFrame() == 0)
				FavoriteList.removeFile(currentFile);
			else
				FavoriteList.addFavorite(currentFile);

			repaint();
		}

		// Change flag volume
		if (x > 210)
			isChanging = true;

	}

	protected void pointerDragged(int x, int y) {
		if (y < 30 || y > 130 || x < 210)
			isChanging = false;
		if (isChanging) {
			volume = startY - y;
			AudioManager.getInstance().setVolume(volume);
			repaint();
		}
	}

	public void commandAction(Command c, Displayable d) {
		// TODO Auto-generated method stub
//		if (c.equals(cmd_viewList)) {
//			Application.getDisplay().setCurrent(new PlaylistsScreen());
//		}
	}

	private boolean checkTouched(Sprite sp, int x, int y) {
		if (x >= sp.getX() && y >= sp.getY()
				&& x <= (sp.getX() + sp.getWidth())
				&& y <= (sp.getY() + sp.getHeight())) {
			return true;
		}
		return false;
	}

	// End touch and command methods

	/*
	 * Play music
	 */
	private static void playFile(Mp3File file) {
		AudioManager.getInstance().playSample(file);
	}

	private static void loopFile(Mp3File file) {
		AudioManager.getInstance().loopSample(file);
	}
	
	public static void playCurrent(){
		AudioManager.getInstance().playSample(currentFile);
	}

	/*
	 * Notify called when player finish a music
	 */
	public static void Notify() {
		System.out.println("Kết thúc một bài");
		if (isRepeat == true) {
			playFile(currentFile);
			return;
		}
		if (isShuffle) {
			Random rd = new Random();
			int size = list.size();
			currentFileIndex = rd.nextInt(size);
			currentFile = (Mp3File) list.elementAt(currentFileIndex);
			System.out.println("Bai tiep theo: " + currentFileIndex);
			playFile(currentFile);
			return;
		}
		if (currentFileIndex == list.size() - 1) {
			currentFileIndex = 0;
			currentFile = (Mp3File) list.elementAt(currentFileIndex);
		} else {
			currentFileIndex++;
			currentFile = (Mp3File) list.elementAt(currentFileIndex);
		}
		playFile(currentFile);
	}

	/*
	 * CategoryBar
	 */
	private void createCategoryBar() {
		Vector commands = new Vector();
		Image imgList = null;
		Image imgList2 = null;
		Image imgList3 = null;
		try {
			imgList = Image.createImage("/category_play.png");
			imgList2 = Image.createImage("/icon_book_list.png");
			imgList3 = Image.createImage("/category_favorite.png");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("EX");
		}

		commands.addElement(new IconCommand("list", imgList, null,
				Command.SCREEN, 1));
		commands.addElement(new IconCommand("list2", imgList2, null,
				Command.SCREEN, 1));
		commands.addElement(new IconCommand("list3", imgList3, null,
				Command.SCREEN, 1));

		IconCommand[] iconCommands = new IconCommand[3];

		for (int i = 0; i < 3; i++) {
			iconCommands[i] = (IconCommand) commands.elementAt(i);
		}

		CategoryBar categoryBar = new CategoryBar(iconCommands, true);
		categoryBar.setElementListener(this);
		Application.setCategoryBar(categoryBar, true);
	}

	public void notifyElementSelected(CategoryBar bar, int selectedIndex) {
		// TODO Auto-generated method stub
		switch (selectedIndex) {
		case 0:
			//AudioManager.getInstance().stopAll();
			Application.getDisplay().setCurrent(PlayScreen.getInstance());
			break;
		case 1:
			//AudioManager.getInstance().stopAll();
			Application.getDisplay().setCurrent(new PlaylistsScreen());
			break;
		case 2:
			ListMusic lm2 = new ListMusic("Favorites", List.IMPLICIT);
			lm2.createListMusic(FavoriteList.getInstance().getListFavorite());
			Application.getDisplay().setCurrent(lm2);
			break;
		case -1:
			Application.getInstance().notifyDestroyed();
			break;
		default:
			break;
		}
		
	}
}
